# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import datetime
import hashlib
from web_lib.page import Page
from web_lib.webutils import Response, expose, json, salvaInSessione, leggiInSessione, permalinkaTitle
import Environment
from dao.User import User as Utente   # tabella utente
from dao.Role import Role
from web_lib.session import Session as S
from lib.utils import prep2json
from webEnv import *


@expose('/pg/ac_Utente/<action>')
@expose('/pg/ac_Utente/')
#@expose('/pg/ac_Faq')
def anagraficaUtente(req, action=None):
    """
            Column('id', Integer, primary_key=True),
        #Column('username', String(50), nullable=False),
        Column('password', String(50), nullable=False),
        #Column('email', String(70), nullable=True),
        #Column('registration_date', DateTime,ColumnDefault(datetime.datetime.now)),
        Column('last_modified', DateTime),
        Column('photo_src', String(150), nullable=True),
        #Column('id_role', Integer, ForeignKey(fk_prefix_main+'role.id',onupdate="CASCADE",ondelete="RESTRICT")),
        #Column('active', Boolean, default=False),
        Column('schemaa_azienda', String(100), ForeignKey(fk_prefix_main+'azienda.schemaa'), nullable=True),
        Column('tipo_user', String(50), nullable=True),
        Column('id_language', Integer,ForeignKey(fk_prefix_main+'language.id')),
        Column('email_confirmed', Boolean, default=False),
        Column('privacy', Boolean, default=False),
        Column('mailing_list', Boolean, default=False),
    """
    #from dao.Setconf import SetConf
    def __show__(req, action=None):
        pageData = {'file': "/pg/ac_Utente"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_username = req.form.get("fk_username")
        fk_email = req.form.get("fk_email")
        fk_id_role = req.form.get("fk_id_role")
        daos = Utente().select(
                            batchSize=batchSize,
                            usern=fk_username,
                            email=fk_email,
                            idRole=fk_id_role,
                            offset=offset,
                            orderBy=sorting)
        count = Utente().count(
                            usern=fk_username,
                            email=fk_email,
                            idRole=fk_id_role,
                            batchSize=None)

        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        id = req.form.get("id")
        if id and id != "None":
            d = Utente().getRecord(id=int(id))
        else:
            d = Utente()
        ruoli = Role().select(batchSize=None)
        pageData = {'file': "pg/addedit/ae_utente",
                    "dao": d,
                    "ruoli":ruoli,
                    }
        return Page(req).render(pageData)



    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        idrr = S(req).getUserId()
        id = req.form.get("id")

        if id != "None":
            d = Utente().getRecord(id=int(id))
        else:
            d = Utente()

        d.email = str(req.form.get("email"))
        d.mailing_list = bool(req.form.get("mailing_list"))
        d.privacy = bool(req.form.get("privacy"))
        d.active = bool(req.form.get("active"))
        d.last_modified = datetime.datetime.now()
        if not id:
            d.registration_date = datetime.datetime.now()
        d.id_role = int(req.form.get("id_role"))
        if id != "None":
            if str(req.form.get("username")) != d.username:
                d.username = str(req.form.get("username"))
                if len(str(req.form.get("password"))) > 5:
                    d.password = hashlib.md5(str(req.form.get("username")) + \
                                    str(req.form.get("password"))).hexdigest()
                #else:
                    #url_red = "/pg/ac_Utente/"
                    #return Page(req).redirect(url_red)
            if req.form.get("password") != "" and d.password != hashlib.md5(str(req.form.get("username")) + str(req.form.get("password"))).hexdigest():
                d.password = hashlib.md5(str(req.form.get("username")) + \
                                str(req.form.get("password"))).hexdigest()

        else:
            d.username = str(req.form.get("username"))
            d.password = hashlib.md5(str(req.form.get("username")) + \
                            str(req.form.get("password"))).hexdigest()
        d.persist()
        url_red = "/pg/ac_Utente/"
        return Page(req).redirect(url_red)



    def __delete__(req, action=None):
        """Cancella una riga"""
        id = int(req.form.get("id"))
        d = Faq().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __get_ruoli__(req, action=None, tipo=None):
        tai = Role().select(batchSize = None)
        tipo= req.args.get("tipo")
        item = [{"id":d.id,"name":str(d.name)} for d in tai]
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __preview__(req, action=None):
        id = req.form.get("id")
        #if id != "None":
        #salvaInSessione(req, chiave="id_fornitore_selezionato", valore=id)
        d = Utente().getRecord(id=id)
        pageData = {'file': "/pg/utente",
                    "dao": d}
        return Page(req).render(pageData)


    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    elif action == "GetRuolo":
        return __get_ruoli__(req, action=action)
    else:
        return __show__(req, action=action)
